package com.rocker.graduation.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;
import com.rocker.graduation.constants.Constants;
import com.rocker.graduation.entity.ErrorBean;
import com.rocker.graduation.entity.UserBean;
import com.rocker.graduation.service.IUserService;
import com.rocker.graduation.util.CaptchaUtils;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/signin.action")
	@ResponseBody
	public ErrorBean signIn(HttpServletRequest request, @RequestBody UserBean user){
		ErrorBean errorBean = new ErrorBean();
		boolean isExist = userService.checkUser(user);
		if (!isExist) {
			errorBean.setSuccess(Constants.FAILED);
		}else {
			request.getSession().setAttribute(Constants.USER_NAME, user.getUserName());
			request.getSession().setAttribute(Constants.USER_ID, user.getUserId());
		}
		
		return errorBean;
	}
	
	@RequestMapping("/signup.action")
	@ResponseBody
	public ErrorBean signUp(@RequestBody UserBean user, HttpServletRequest request){
		ErrorBean errorBean = new ErrorBean();
		boolean isSuccess = userService.saveUser(user);
		if (!isSuccess) {
			errorBean.setSuccess(Constants.FAILED);
		}else {
			WebUtils.setSessionAttribute(request, Constants.USER_ID, user.getUserId());
			WebUtils.setSessionAttribute(request, Constants.USER_NAME, user.getUserName());
		}
		return errorBean;
	}
	
	@RequestMapping("/signout.action")
	@ResponseBody
	public ErrorBean signOut(HttpServletRequest request){
		ErrorBean errorBean = new ErrorBean();
		request.getSession().invalidate();
		return errorBean;
	}
	
	@RequestMapping("/success.action")
	public String registerSuccess(@RequestParam String url, HttpServletRequest request){
		WebUtils.setSessionAttribute(request, Constants.URL, url);
		return "/success";
	}
	
	@RequestMapping("/getCaptcha.action")
	public ModelAndView getCaptchaImage(HttpServletRequest request, HttpServletResponse response){
		response.setDateHeader("Expires", 0);     
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");    
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");    
        response.setHeader("Pragma", "no-cache");    
        response.setContentType("image/png");
        
        try {
			String token = EncoderHelper.getChallangeAndWriteImage(CaptchaUtils.getCaptcha(), "png", response.getOutputStream());
			WebUtils.setSessionAttribute(request, Constants.CAPTCHA_SESSION_KEY, token);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
        
		return null;
	}
	
	@RequestMapping("/isUsernameEngaged.action")
	@ResponseBody
	public ErrorBean checkUserName(@RequestParam String username) {
		ErrorBean errorBean = new ErrorBean();
		boolean isExist = userService.isEngaged(username, 1);
		if (isExist) {
			errorBean.setSuccess(Constants.FAILED);
		}
		return errorBean;
	}
	
	@RequestMapping("/isEmailEngaged.action")
	@ResponseBody
	public ErrorBean isEmailEngaged(@RequestParam String email) {
		ErrorBean errorBean = new ErrorBean();
		boolean isExist = userService.isEngaged(email, 2);
		if (isExist) {
			errorBean.setSuccess(Constants.FAILED);
		}
		return errorBean;
	}
	
	@RequestMapping("/verify.action")
	@ResponseBody
	public ErrorBean checkCaptcha(@RequestParam String token, HttpServletRequest request){
		ErrorBean errorBean = new ErrorBean();
		String key = (String) WebUtils.getSessionAttribute(request, Constants.CAPTCHA_SESSION_KEY);
		if (!token.toLowerCase().equals(key.toLowerCase())) {
			errorBean.setSuccess(Constants.FAILED);
		}
		return errorBean;
	}
	
	@RequestMapping("/facade.action")
	public ModelAndView showSignin4User(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession(false);
		if (null == session) {
			session = request.getSession(true);
		}
		mav.setViewName("/user");
		return mav;
	}
}
